package framework
{
    import flash.utils.describeType;
    import flash.utils.getDefinitionByName;

    public class Utils
    {
        public static function propertyExists(prop:String, host:Object):Boolean
        {
            if (!prop)
                return false;
            var c:Array = prop.split(".");
            while (c.length > 0)
            {
                if (host && c[0] in host)
                {
                    host = host[c[0]];
                    c.shift();
                }
                else
                    return false;
            }
            return true;
        }

        public static function setProperty(prop:String, host:Object, value:Object):void
        {
            if (!prop || !host)
                return;
            var c:Array = prop.split(".");
            while (c.length > 1)
            {
                host = host[c[0]];
                c.shift();
            }
            host[c[0]] = value == "false" ? false : value;
        }
		 public static function getProperty(host:Object,prop:String):*
		 {
		 	if (!prop || !host) return void;
		 	var c:Array = prop.split(".");
		    while (c.length > 0)
		    {
				host = host[c[0]];
				c.shift();
			}
			return host;
		 }

        public static function copyObjectProperties(source:Object, dest:Object, prefixes:Array = null, ignore:Array = null):void
        {
            var d:XML = describeType(source);
            for each (var prop:XML in d..variable)
            {
                var n:String = prop.@name;
                if (ignore && ignore.indexOf(n) != -1)
                    continue;
                if (prefixes && !hasPrefix(prefixes, n))
                    continue;
                copyValue(n, source, dest);
            }
            for each (prop in d..accessor)
            {
                n = prop.@name;
                if (ignore && ignore.indexOf(n) != -1)
                    continue;
                if (prefixes && !hasPrefix(prefixes, n))
                    continue;
                copyValue(n, source, dest);
            }
        }

        private static function hasPrefix(prefix:Array, n:String):Boolean
        {
            for each (var s:String in prefix)
            {
                if (n.indexOf(s) == 0)
                    return true;
            }

            return false;
        }

        private static function copyValue(name:String, source:Object, dest:Object):void
        {
            try
            {
                dest[name] = source[name];
            }
            catch (e:Error)
            {

            }
        }
        
        public static function callLater(func:Function, args:Array = null):void
        {
        	var clazz:Class = getDefinitionByName("mx.core.Application") as Class;
        	clazz["application"].callLater(func, args);
        }

    }
}